package com.example.demo.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import com.example.demo.util.EmptyUtil;
import com.example.demo.util.PropertiesUtil;
import com.example.demo.util.RedisUtil;
import com.example.demo.util.RequestLoginCache;
import com.example.demo.util.TokenUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Order(1)
@WebFilter(filterName="authfilter",urlPatterns="/*")
public class AuthFilter implements Filter{
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Value("${server.servlet.context-path}")
	private String contentPath;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		log.info("登陆过滤器创建...");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest)request;
		
		HttpServletResponse resp = (HttpServletResponse)response;
		
		boolean allowPass = false;
		
		String token = TokenUtil.getTokenFromRequest(req);
		
		String uri = req.getRequestURI();
		
		if(EmptyUtil.isNotEmpty(token)) {
			allowPass = true;
		}
		
		if(uri.equals(contentPath+"/") || "/".equals(uri)) {//如果是访问默认登录页面,直接放行
			chain.doFilter(request, response);
			return;
		}
		
		//验证token是否过期
		if(allowPass) {
			try {
				allowPass = redisUtil.checkToken(token);
				if(allowPass) {
					//本次请求缓存登录信息
					RequestLoginCache.set(redisUtil.getLoginInfoByToken(token));
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				allowPass = false;
			}
		}
		
		
		
		String ignoreFilter = PropertiesUtil.getProperty("ignoreFilter");
		
		String[] ignores = ignoreFilter.split("\\|"); 
		
		int len = ignores.length;
		
		for (int i = 0; i < len; i++) {
			if(uri.toLowerCase().indexOf(ignores[i])>-1) {
				allowPass = true;
				break;
			}
		}
		//屏蔽登陆验证
//		allowPass = true;
		if(allowPass) {
			chain.doFilter(request, response);
		}else {
			log.debug("无法通过的请求：{}",uri);

			if(EmptyUtil.isNotEmpty(req.getHeader("X-Requested-With"))&&"XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
				//如果是ajax请求,则设置返回编码为800，前端通过判断跳转到登陆页
				resp.setStatus(800);
				return;
			}
			
			String networkProtocal = req.getScheme();
			String ip = req.getServerName();
			int port = req.getServerPort();
			String contextPath = req.getContextPath();
			
			StringBuilder targetHtml = new StringBuilder();
//			targetHtml.append(networkProtocal).append("://").append(ip).append(":").append(port).append(contextPath).append("/login.html");
			targetHtml.append(contextPath).append("/login.html");
			
			log.debug("跳转的页面-->{}",targetHtml);
			
			StringBuilder layuiPath = new StringBuilder();
//			layuiPath.append(networkProtocal).append("://").append(ip).append(":").append(port).append(contextPath).append("/layui/layui.js");
			layuiPath.append(contextPath).append("/layui/layui.js");
			log.debug("layui.js的路径-->{}",layuiPath);
			
			resp.reset();
			resp.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print("<script type='text/javascript' src='"+layuiPath.toString()+"'></script>\n");
			out.print("<script type='text/javascript'>\n");
			out.print("layui.use('layer', function(){\n");
			out.print("layer.msg('未通过登陆验证，不允许访问  ',{\n");
			out.print("time : 0\n");
			out.print(",offset : '200px'\n");
			out.print(",area : ['250px','100px']\n");
			out.print(",shade : [0.3]\n");
			out.print(",btn : ['确定']\n");
			out.print(",btnAlign : 'c'\n");
			out.print(",yes : function(index){\n");
			out.print("window.parent.location.href = '"+targetHtml.toString()+"';\n");
			out.print("}\n");
			out.print("})\n");
			out.print("});\n");
			out.print("</script>");
			out.close();
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		log.info("登陆过滤器销毁...");
	}
}
